package restful.jersey.client;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import restful.JAXBContextResolver;
import restful.domain.SimplePOJO;
import restful.domain.SimplePOJOList;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class JerseyClient {
	private Client c;
	
	public JerseyClient() {
 		ClientConfig cc = new DefaultClientConfig();
		// use the following jaxb context resolver
		cc.getClasses().add(JAXBContextResolver.class);
		c = Client.create(cc);
	}
	
	// Fetch a simple string from ws
	public void clientTest() {
		WebResource r = c.resource("http://localhost:8080/RESTWSTest/jersey/hello");
		String response = r.accept(MediaType.TEXT_HTML).get(String.class);
		System.out.println("response : " + response);
	}
	
	// Fetch a response from ws by using form
	public void getResponse() {
		WebResource r = c.resource("http://localhost:8080/RESTWSTest/jersey/hello/form");
		MultivaluedMap<String, String> formParam = new MultivaluedMapImpl();
		formParam.add("name", "blurmfromform");
		formParam.add("age", "33");
		ClientResponse response = r.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParam);
		String res = response.getEntity(String.class);
		System.out.println(res);
	}
	
	// Fetch a response from ws by using query parameter
	public void getResponseByQM() {
		
		MultivaluedMap<String, String> queryParam = new MultivaluedMapImpl();
		queryParam.add("name", "blurmfromQuery");
		queryParam.add("age", "31");
		WebResource r = c.resource("http://localhost:8080/RESTWSTest/jersey/hello/query").queryParams(queryParam);
		// Add Log filter
		c.addFilter(new LoggingFilter(System.out));
		ClientResponse response = r.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
		String res = response.getEntity(String.class);
		System.out.println(res);
	}
	
	// Fetch json response
	public void getJSONResponse() {
		WebResource r = c.resource("http://localhost:8080/RESTWSTest/jersey/hello/json/simple");
		SimplePOJO pojo = r.accept(MediaType.APPLICATION_JSON).get(SimplePOJO.class);
		pojo.toString();
	}
	
	public void getJSONListResponse() {
		WebResource r = c.resource("http://localhost:8080/RESTWSTest/jersey/hello/json/list");
		String pojoList = r.accept(MediaType.APPLICATION_JSON).get(String.class);
		System.out.println(pojoList);
	}
}
